define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    var $pricelabel = $('[data-toggle="pricelabel"]');
    var $activitylabel = $('[data-toggle="activitylabel"]');

    if (window.freeship_data) {
        //赋值
        template.helper('pricelabel_selected', function(id, selected) {
            return window.freeship_data.pricelabel[id] == selected ? 'checked="checked"' : config.empty
        });
        template.helper('pricelabel_checked', function(id, selected) {
            return window.freeship_data.pricelabel[id] == selected ? 'class="active"' : config.empty
        });
        template.helper('activitylabel_selected', function(id, selected) {
            return window.freeship_data.activitylabel[id] == selected ? 'checked="checked"' : config.empty
        });
        template.helper('activitylabel_checked', function(id, selected) {
            return window.freeship_data.activitylabel[id] == selected ? 'class="active"' : config.empty
        });
        
    } else {
        template.helper('pricelabel_selected', function(id, selected) {
            return config.empty;
        });
        template.helper('activitylabel_selected', function(id, selected) {
            return config.empty;
        });
       /* template.helper('specifications_checked', function(id, checked) {
            return config.empty;
        });*/
    }
    var priceinit = function(custom) {
        method.get(window.freeship_setting.pricelabel_path, function(data) {
            if (config.issucceed(data)) {
                $pricelabel.html(template("pricelabel_template", data.data));
                $(".js_pricelabel_list li").each(function() {
                    var $this = $(this),
                        $ul = $this.closest("ul"),
                        id = $ul.attr("id"),
                        text = $ul.find(".active input[type='radio']:checked").data("title");
                    $("#label_" + id).html(text);
                });
            }else{
                config.msg.error(data.message);
            }
        }, config.lang.pricelabelError);
        custom.customInput();
        $(document).on("click", ".js_pricelabel_list .js_custom_btn", function() {
            $(this).parents(".js_custom_list").prev(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
            var $p = $(this).parents(".custom-select");
            $p.scrollTop($p.get(0).scrollHeight - 0 + 60);
        });
        $(document).on("click", ".js_pricelabel_list .js_custom_list_save", function() {
            var input = $(this).parents(".js_custom_list").find(".js_custom_input"),
                name = $(this).data("name"),
                tdata = custom.customdata(input);
            if (custom.customValvali(input) && input.val()) {
                if (custom.getValExist(input.val(), tdata.id)) {
                    config.msg.info("已经存在的属性值");
                } else {
                    custom.addVal(tdata, name, input, false, $(this),window.freeship_setting.custom_pricevalue_path);
                }

            }
            if (!input.val()) {
                config.msg.error("属性值为空！");
            }
        });
        $(document).on("click", ".js_pricelabel_list .js_custom_list_cancel", function() {
            $(this).parents(".js_custom_list").next(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
        });
        $(document).on("click", ".js_pricelabel_list .js_custom_del", function() {
            var input = $(this).prev("a").find("input[type='radio']"),
                valid = input.val();
            method.post(window.freeship_setting.custom_pricevalue_del_path, function(data) {
                if (config.issucceed(data)) {
                    if (input.prop("checked")) {
                        $("#label_" + input.data("id")).html("选择");
                    } else {
                        if (!custom.getValExist($("#label_" + input.data("id")).text(), input.data("id"))) {
                            $("#label_" + valid).html("选择");
                        }
                    }
                    input.parents("li").remove();
                    config.msg.info(data.message || config.lang.removeSuccess);
                } else {
                    config.msg.error(data.message);
                }

            }, config.lang.pricelabelError, false, {
                "id": input.data("id"),
                "valid": valid
            });
        });
    }
    var activityinit = function(custom) {
        method.get(window.freeship_setting.activitylabel_path, function(data) {
            if (config.issucceed(data)) {
                $activitylabel.html(template("activitylabel_template", data.data));
                $(".js_activitylabel_list li").each(function() {
                    var $this = $(this),
                        $ul = $this.closest("ul"),
                        id = $ul.attr("id"),
                        text = $ul.find(".active input[type='radio']:checked").data("title");
                    $("#label_" + id).html(text);
                });
            }else{
                config.msg.error(data.message);
            }
           
        }, config.lang.activitylabelError);
        custom.customInput();
        $(document).on("click", ".js_activitylabel_list .js_custom_btn", function() {
            $(this).parents(".js_custom_list").prev(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
            var $p = $(this).parents(".custom-select");
            $p.scrollTop($p.get(0).scrollHeight - 0 + 60);
        });
        $(document).on("click", ".js_activitylabel_list .js_custom_list_save", function() {
            var input = $(this).parents(".js_custom_list").find(".js_custom_input"),
                name = $(this).data("name"),
                tdata = custom.customdata(input);
            if (custom.customValvali(input) && input.val()) {
                if (custom.getValExist(input.val(), tdata.id)) {
                    config.msg.info("已经存在的属性值");
                } else {
                    custom.addVal(tdata, name, input, false, $(this),window.freeship_setting.custom_activityvalue_path);
                }

            }
            if (!input.val()) {
                config.msg.error("属性值为空！");
            }
        });
        $(document).on("click", ".js_activitylabel_list .js_custom_list_cancel", function() {
            $(this).parents(".js_custom_list").next(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
        });
        $(document).on("click", ".js_activitylabel_list .js_custom_del", function() {
            var input = $(this).prev("a").find("input[type='radio']"),
                valid = input.val();
            method.post(window.freeship_setting.custom_activityvalue_del_path, function(data) {
                if (config.issucceed(data)) {
                    if (input.prop("checked")) {
                        $("#label_" + input.data("id")).html("选择");
                    } else {
                        if (!custom.getValExist($("#label_" + input.data("id")).text(), input.data("id"))) {
                            $("#label_" + valid).html("选择");
                        }
                    }
                    input.parents("li").remove();
                    config.msg.info(data.message || config.lang.removeSuccess);
                } else {
                    config.msg.error(data.message);
                }

            }, config.lang.activitylabelError, false, {
                "id": input.data("id"),
                "valid": valid
            });
        });
    }
    var Custom = function() {

    }
    Custom.prototype.customInput = function() {
        var _this = this;
        $(document).on("keyup", ".js_custom_input", function() {
            var len = _this.getInputLen($(this)),limit=$(this).data("limit"),
                limitmin = limit[0] - 0,
                limitmax = limit[1] - 0,
                $limit = $(this).next(".js_limit");
            $limit.find("em").html(Math.ceil(len / 2));
            if (len > limitmax * 2 || len<limitmin*2) {
                $limit.addClass('error');
            } else {
                $limit.removeClass('error');
            }
        });
    }
    Custom.prototype.getInputLen = function(input) {
        return input.val().replace(/[^\x00-\xff]/g, "xx").length;
    }
    Custom.prototype.customdata = function(input) {
        return {
            "id": input.data("id"),
            "val": input.val()
        }
    }
    Custom.prototype.customValvali = function(input) {
        var flag = true,
            limit = input.data("limit"),
            limitmin = limit[0] - 0,
            limitmax = limit[1] - 0,
            len = this.getInputLen(input);
        if (len<=limitmax * 2 && len>=limitmin * 2) {
            flag = true;
        } else {
            flag = false;
        }
        return flag;

    }
    Custom.prototype.getValExist = function(val,id) {
        var arr = [],
            flag, isexist;
        $("#" + id).find("input[type='radio']").each(function() {
            if ($(this).val()) {
                arr.push($(this).data("title"));
            }
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        return flag;
    }
    Custom.prototype.addVal = function(tdata, name, input, isattr, button,path) {
        var _this = this;
        button.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>提交中');
        button.button('loading');
        $.ajax(path, {
            type: "post",
            data: tdata,
            dataType: "json"
        }).done(function(d) {
            button.button('reset');
            if (config.issucceed(d)) {
                var data=d.data;
                d.data.checked = true;
                d.data.name = name;
                _this.result(d.data, input, isattr);
            } else {
                config.msg.error(d.message);
            }

        }).fail(function() {
            button.button('reset');
            config.msg.info(config.lang.exception)
        });
    }
    Custom.prototype.result = function(data, input, isattr) {
        var $target = $("#" + data.id).find(".js_custom_list:first");
        $("#" + data.id).find("li").removeClass("active");
        $("#" + data.id).find("li input[type='radio']").removeAttr("checked");
        $(template("customval_tem", data)).insertBefore($target);
        $("#label_" + data.id).html(data.title);
        $("#label_" + data.id).removeClass('error');
        $(document).trigger('click');
        input.val("");
        input.next(".js_limit").find("em").html(0);
        $target.addClass('hide');
        $target.next(".js_custom_list").removeClass('hide');
        $("#" + data.id).find(".js_search_result").addClass('hide');
        config.msg.info(config.lang.saveSuccess);
    }
    $pricelabel.length>0&&priceinit(new Custom());
    $activitylabel.length>0&&activityinit(new Custom());
    $(".js_add_privilege").length&&(function(){
        if($(".js_privilege_list").length==5){
            $(".js_add_privilege").addClass('hide');
            $(".js_add_privilege").closest('.form-group').next(".line-dashed").addClass('hide');
        }
    })();
    $(document).on("click",".js_add_privilege",function(){
        var $this=$(this),$target=$this.closest('.form-group'),index=$(".js_privilege_list:last").data("num")-0+1,
        discp=$(".js_discount_check:first").prop("checked"),minusp=$(".js_minus_check:first").prop("checked"),flag="",
        content1=$(".js_content1:checked").length,content2=$(".js_content2:checked").length,content="";
        if(discp){
            flag="js_discount_check";
        } 
        if(minusp){
            flag="js_minus_check";
        }
        if(content1){
            content="js_content1";
        } 
        if(content2){
            content="js_content2";
        }
        if($(".js_privilege_list").length==4){
            $this.addClass('hide');
            $target.next(".line-dashed").addClass('hide');
        }
        //$(".js_del_privilege").addClass('hide');
        $(template("privilege_template",{"num":index+1,"index":index,"select":flag,"content":content})).insertBefore($target);
        $('[data-toggle="popover"]').popover();
    });
    $(document).on("click",".js_discount_check:first",function(){
        var $this=$(this),checked=$this.prop("checked"),$minus=$(".js_minus_input"),$discp=$(".js_discount_input");
        if(checked){
            $minus.prop("disabled",true);
            $minus.prop("readonly",false); 
            $(".js_discount_check").prop("checked",true).attr("disabled",false) 

            $(".js_minus_check").prop("disabled",true);
            $(".js_minus_check:first").prop("disabled",false);
            $(".js_minus_check").each(function(){
                var $this=$(this),$target=$this.closest('.form-group');
                $target.find("input[type='text']").removeClass('error');
                $target.find("span.error").remove();
            });
            $discp.prop("disabled",false);
            $discp.prop("readonly",false);
        }
    });
    $(".js_minus_check").length>0&&(function(){
        var $minus=$(".js_minus_check:checked"),$disc=$(".js_discount_check:checked"),
        $content1=$(".js_content1:checked"),$content2=$(".js_content2:checked");
        if($minus.length){
            $(".js_minus_input").prop("disabled",false);
            $(".js_discount_check").prop("disabled",true);
            $(".js_discount_check:first").prop("disabled",false);
        }else{
            $(".js_minus_input").prop("disabled",true);
            $(".js_discount_check").prop("disabled",false);
        }
        if($disc.length){
            $(".js_discount_input").prop("disabled",false);
            $(".js_minus_check").prop("disabled",true);
            $(".js_minus_check:first").prop("disabled",false);
        }else{
            $(".js_discount_input").prop("disabled",true);
        }
        if($content1.length){
            $(".js_content2").prop("disabled",true);
            $(".js_content2:first").prop("disabled",false);
            $(".js_cap").prop("disabled",true);
        }else{
           $(".js_content_input1").prop("disabled",true);
        }
        if($content2.length){
           $(".js_content1").prop("disabled",true);
           $(".js_content1:first").prop("disabled",false);
        }else{
           $(".js_content_input2").prop("disabled",true);
        }
    })();
    $(document).on("click",".js_minus_check:first",function(){
        var $this=$(this),checked=$this.prop("checked"),$minus=$(".js_minus_input"),$discp=$(".js_discount_input");
        if(checked){
            $minus.prop("disabled",false);
            $minus.prop("readonly",false);
            $(".js_minus_check").prop("checked",true).attr("disabled",false) 
            $(".js_discount_check").each(function(){
                var $this=$(this),$target=$this.closest('.form-group');
                $target.find("input[type='text']").removeClass('error');
                $target.find("span.error").remove();
            });
            $(".js_discount_check").prop("disabled",true);
            $(".js_discount_check:first").prop("disabled",false);
            $discp.prop("disabled",true);
            $discp.prop("readonly",true);
        }
    });
    $(document).on("click",".js_content1",function(){
        var $this=$(this),checked=$this.prop("checked"),$minus=$(".js_content_input2"),$discp=$(".js_content_input1");
        var flag=$(".js_content1:checked").length,$input=$this.closest('.form-group').find(".js_content_input1");
        if(checked){
            $minus.prop("readonly",true);
            $minus.prop("disabled",true);
            $(".js_content1").prop("disabled",false);
            $(".js_content2").prop("checked",false);
            $(".js_content2").prop("disabled",true);
            $(".js_content2:first").prop("disabled",false);
            $(".js_content2").each(function(){
                var $this=$(this),$target=$this.closest('.form-group');
                $target.find("input[type='text']").removeClass('error');
                $target.find("span.error").remove();
            });
            $(".js_cap").prop("disabled",true);
            $(".js_cap").prop("checked",false);
            $input.prop("readonly",false);
            $input.prop("disabled",false);
        }else{
            $input.prop("readonly",true);
            $input.prop("disabled",true);
            var $this1=$(".js_content1"),$target1=$this1.closest('.form-group');
            $target1.find("input[type='text']").removeClass('error');
            $target1.find("span.error").remove();
            if(!flag){
                $(".js_content2").prop("disabled",false);
            }
        }
    });
    
    $(document).on("click",".js_content2",function(){
        var $this=$(this),checked=$this.prop("checked"),$minus=$(".js_content_input2"),$discp=$(".js_content_input1");
        var flag=$(".js_content1:checked").length,$input=$this.closest('.form-group').find(".js_content_input2");
        if(checked){
            $discp.prop("readonly",true);
            $discp.prop("disabled",true);
            $(".js_content2").prop("disabled",false);
            $(".js_content1").prop("checked",false);
            $(".js_content1").prop("disabled",true);
            $(".js_content1:first").prop("disabled",false);
            $(".js_content1").each(function(){
                var $this=$(this),$target=$this.closest('.form-group');
                $target.find("input[type='text']").removeClass('error');
                $target.find("span.error").remove();
            });
            $(".js_cap",$this.closest('.form-group')).prop("disabled",false);
            $input.prop("readonly",false);
            $input.prop("disabled",false);
        }else{
            $input.prop("readonly",true);
            $input.prop("disabled",true);
            $(".js_cap",$this.closest('.form-group')).prop("disabled",true);
            var $this2=$(".js_content2"),$target2=$this2.closest('.form-group');
            $target2.find("input[type='text']").removeClass('error');
            $target2.find("span.error").remove();
            if(!flag){
                $(".js_content1").prop("disabled",false);
            }
        }
    });
    $(document).on("click",".js_del_privilege",function(){
        var $this=$(this),$target=$this.closest('.js_privilege_list');
        $target.remove();
        $(".js_add_privilege").removeClass("hide");
        $(".js_del_privilege:last").removeClass("hide");
    });
    /*$(document).on("click",".js_free",function(){
        var flag=$(this).prop("checked"),$target=$(this).closest('.js_privilege_list'),
        $input1=$(".js_content_input1",$target),$input2=$(".js_content_input2",$target);
        if(flag){
            $target.find(".js_content_input1,.js_content_input2").addClass('ignore');
            $input1.removeClass('error');
            $input2.removeClass('error');
            $input1.closest('.form-group').find("span.error").remove();
            $input2.closest('.form-group').find("span.error").remove();
        }else{
            $target.find(".js_content_input1,.js_content_input2").removeClass('ignore');
        }
    });*/
    $(document).on("click",".js_lottery",function(){
        var $this=$(this),flag=$this.prop("checked"),$target=$(".js_lottery_input",$this.closest('.form-group'));
        if(flag){
            $target.prop("disabled",false); 
        }else{
            $target.prop("disabled",true); 
        }
    });
    $(".js_minus_input").length>0&&$(document).on("click","button[type='submit']",function(){
        var flag=true,input1=[],checked=$(".js_minus_input:first").prop("disabled");
        if(!checked){
            $(".js_minus_input").each(function(){
                var val=$(this).val();
                if(val && val.length>0){
                    input1.push(val);
                }
            });
        }else{
            $(".js_discount_input").each(function(){
                var val=$(this).val();
                if(val && val.length>0){
                    input1.push(val);
                }
            });
        }
        flag=!isRepeat(input1);
        if(!flag){
            config.msg.error("存在相同的活动条件，请修改");
        }
        return flag;
    });
    $(".js_lottery_input").length>0&&$(document).on("click","button[type='submit']",function(){
        var $lottery_count=$(".js_lottery_count"),msg=$lottery_count.data("msg"),total=$lottery_count.val()-0,count=0,flag=true;
        $(".js_lottery_input").each(function(){
            count+=$(this).val()-0;
        });
        if(count>total){
            flag=false;
        }
        if(!flag){
            config.msg.error(msg||"彩票赠送数量有限哦，请合理分配，再调整一下吧");
        }
        return flag;
    });
    $(".js_minus_input").length>0&&$(document).on("click","button[type='submit']",function(){
        var flag=true,input1=[],checked=$(".js_minus_input:first").prop("disabled");
        $(".js_privilege_list").each(function(){
            var $this=$(this),$content1=$(".js_content1",$this),$content2=$(".js_content2",$this),
            $free=$(".js_free",$this),$lottery=$(".js_lottery",$this);
            console.log($lottery.prop("checked"))
            if(!$content1.prop("checked")&&!$content2.prop("checked")&&!$free.prop("checked")&&!$lottery.prop("checked")){
                flag=false;
            }
        });
        if(!flag){
            config.msg.error("请选择活动内容");
        }
        return flag;
    });
    function isRepeat(arr){
        var hash = {};
        for(var i in arr) {
            if(hash[arr[i]])
              return true;
            hash[arr[i]] = true;
        }
        return false;
    }
    $activitylabel.length>0&&$(document).on("click","button[type='submit']",function(){
        var $selected=$activitylabel.find(".js_activitylabel_list input[type='radio']:checked");
        if($selected.val()==undefined||$selected.val()==""){
            config.msg.error("请选择活动标签");
            return false;
        }
    });
})
